package org.dllwh.mongo;

import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.dialect.Props;
import cn.hutool.setting.dialect.PropsUtil;
import com.mongodb.*;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;

/**
 * 把今天最好的表现当作明天最新的起点．．～
 * <p>
 * Today the best performance as tomorrow the newest starter!
 *
 * @ClassName MongoDBConnect
 * @Description MongoDB 连接操作类
 * @Date 2025-06-09 15:59
 * @版本 V 1.0.1
 * @since JDK 17
 */
public class MongoDBConnect {
    private static MongoClient mongoClient = null;
    private static final Props MONGO_PROPERTIES = PropsUtil.get("mongo.properties");
    private static final String HOST = MONGO_PROPERTIES.getStr("host");
    private static final String PORT = MONGO_PROPERTIES.getStr("port");
    private static final String DATABASE = MONGO_PROPERTIES.getStr("database");
    private static final String USER_NAME = MONGO_PROPERTIES.getStr("username");
    private static final String PASSWORD = MONGO_PROPERTIES.getStr("password");

    private MongoDBConnect() {
    }

    /**
     * 获取 MongoDB 客户端，使用连接字符串建立数据库连接
     * <p>
     * 若已建立连接，则直接返回已建立的连接。若未建立连接，则建立连接并返回。避免频繁建立连接导致性能下降
     *
     * @throws MongoException 异常
     */
    public static MongoClient getMongoClient() throws MongoException {
        String connectionString;
        if (mongoClient == null) {
            if (StrUtil.isNotBlank(USER_NAME) && StrUtil.isNotBlank(PASSWORD) && StrUtil.isNotBlank(DATABASE)) {
                connectionString = String.format("mongodb://%s:%s@%s:%s/%s", USER_NAME, PASSWORD, HOST, PORT, DATABASE);
            } else {
                connectionString = String.format("mongodb://%s:%s", HOST, PORT);
            }
            mongoClient = MongoClients.create(connectionString);
        }
        return mongoClient;
    }

    /**
     * 获取 MongoDB 客户端，使用用户名密码建立数据库连接
     *
     * @throws MongoException 异常
     */
    public static MongoClient getMongoAuthClient() throws MongoException {
        if (mongoClient == null) {
            // 创建一个封装用户认证信息
            MongoCredential credential = MongoCredential.createCredential(USER_NAME, DATABASE, PASSWORD.toCharArray());
            String connectionString = String.format("mongodb://%s:%s", HOST, PORT);
            MongoClientSettings.Builder build = MongoClientSettings.builder();
            build.applyConnectionString(new ConnectionString(connectionString));
            build.credential(credential);
            return MongoClients.create(build.build());
        }
        return mongoClient;
    }

    /**
     * 关闭 MongoDB 客户端
     */
    public static void closeMongoClient(MongoClient mongoClient) {
        mongoClient.close();
    }
}
